package common.interceptor;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.zdxc.entities.Userinfo;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;



import common.constant.GlobalConstant;
import common.util.UserInfoUtils;

/**
 * 用户权限拦截器
 * 
 * @author liuxj
 * @version 1.0.0 2017-07-10
 */
public class AuthorityInterceptor extends HandlerInterceptorAdapter {
    private static final Logger LOGGER = Logger.getLogger(AuthorityInterceptor.class);
    
    /** 配置不需要登录验证的URI */
    private List<String> excludeLoginUriList;
    
    /** 配置登录以后不需要进行权限验证的URI */
    private List<String> excludeAuthorityUriList;
    
    private PathMatcher pathMatcher = new AntPathMatcher();
    
    private UrlPathHelper urlPathHelper = new UrlPathHelper();
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // preHandle调用controller具体方法之前调用
        
        String errorMsg = (String)request.getAttribute(GlobalConstant.ERROR_MSG_KEY);
        if (StringUtils.isNotBlank(errorMsg)) {
            return true;
        }
        
        // 用户请求的URI
        String uri = urlPathHelper.getLookupPathForRequest(request);
        
        // 判断当前请求是否需要进行拦截
        if (!CollectionUtils.isEmpty(excludeLoginUriList)) {
            for (String excludeUri : excludeLoginUriList) {
                if (pathMatcher.match(excludeUri, uri)) {
                    return true;
                }
            }
        }
        
        // 判断当前请求是否需要进行权限验证
        if (!CollectionUtils.isEmpty(excludeAuthorityUriList)) {
            for (String excludeUri : excludeAuthorityUriList) {
                if (pathMatcher.match(excludeUri, uri)) {
                    return true;
                }
            }
        }
        
        Userinfo User = UserInfoUtils.getUser();
        String userIp = UserInfoUtils.getUserIp();
        String username = null;
        
        if (User != null) {
            username = User.getUserName();
            
            if (username.equals(GlobalConstant.SYS_ADMIN_CODE)) {
                return true;
            }
            

        }
        LOGGER.debug("[" + userIp + "]用户[" + username + "]没有权限访问：" + uri);
        
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.setAttribute(GlobalConstant.ERROR_MSG_KEY, "您没有权限访问该功能！");
        request.getRequestDispatcher("/error").forward(request, response);

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // postHandle完成具体方法之后调用
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // afterCompletion完成对页面的render以后调用，至此整个页面渲染完成
        super.afterCompletion(request, response, handler, ex);
    }

    public List<String> getExcludeLoginUriList() {
        return excludeLoginUriList;
    }

    public void setExcludeLoginUriList(List<String> excludeLoginUriList) {
        this.excludeLoginUriList = excludeLoginUriList;
    }

    public List<String> getExcludeAuthorityUriList() {
        return excludeAuthorityUriList;
    }

    public void setExcludeAuthorityUriList(List<String> excludeAuthorityUriList) {
        this.excludeAuthorityUriList = excludeAuthorityUriList;
    }

}
